import Request from 'luch-request'
import { useUserStore } from '@/stores/user.js'
const userStore = useUserStore()
const whiteList = ['/code', '/login', '/login/password']
const http = new Request({
	baseURL: 'https://consult-api.itheima.net/',
	timeout: 5000,
	custom: {
		loading: true,
	},
})
const defaultHeader = {}
http.interceptors.request.use(
	(config) => {
		if (config.custom.loading) {
			uni.showLoading({
				title: '加载中',
				mask: true,
			})
		}
		if (userStore.token && !whiteList.includes(config.url))
			defaultHeader.Authorization = 'Bearer ' + userStore.token
		config.header = {
			...defaultHeader,
			...config.header,
		}
		return config
	},
	(err) => {
		uni.hideLoading()
		return Promise.reject(err)
	}
)
const tabPages = [
	"/pages/index/index",
	"/pages/my/index",
	"/pages/wiki/index",
	"/pages/notify/index"
]
http.interceptors.response.use(

	({ data }) => {
		uni.hideLoading()
		return data
	},
	(err) => {
		// 超出 2xx 范围的状态码都会触发该函数。
		uni.hideLoading()
		console.log(err)
		if (err.statusCode === 401) {
			reLogin()
		}
		return Promise.reject(err)
	}
)
function reLogin() {
	const pageStack = getCurrentPages()
	console.log(pageStack)
	// 当前页面
	const currentPage = pageStack[pageStack.length-1]
	const redirectURL = currentPage.$page.fullPath
	console.log(redirectURL);
	// 完整的路由
	userStore.redirectURL = redirectURL
	userStore.openType = tabPages.includes(redirectURL)?'switchTab':'redirectTo'
	
	console.log();
	uni.redirectTo({
		url: '/pages/login/index',
	})
}
export default http
